import string
from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from utils.jwt_token import check_login
import random
from captcha.image import ImageCaptcha
from .models import *
from rest_framework.response import Response
import redis
from utils.sms_code import send_message
import jwt
from django.conf import settings
import time
# Create your views here.


# 部门管理(查，增)
class DepartmentView(APIView):
    def get(self,request):
        departments = DepartmentModel.objects.all()
        temp = []
        for item in departments:
            temp.append({
                'id':item.id,
                'dname':item.dname
            })
        return Response({
            'code':200,
            'msg':'获取所有部门成功',
            'data':temp
        })
    @check_login
    def post(self,request):
        user_id = request.user_id
        user = UserModel.objects.get(id=user_id)
        if user_id == 1 or user.role.juris.pathname=='/post':
            dname = request.data.get('dname')
            if not dname:
                return Response({
                    'code':400,
                    'msg':'参数不完整'
                })
            department = DepartmentModel.objects.filter(dname=dname).first()
            if not department:
                DepartmentModel.objects.create(dname=dname)
                return Response({
                    'code':201,
                    'msg':'添加部门成功'
                })
            else:
                return Response({
                    'code':400,
                    'msg':'已有该部门'
                })
        else:
            return Response({
                'code':400,
                'msg':'对不起，您没有该权限'
            })


# 部门管理(查,改，删)
class DepartmentInfoView(APIView):
    def get(self,request,id):
        department = DepartmentModel.objects.get(id=id)
        if not department:
            return Response({
                'code':400,
                'msg':'没有该部门'
            })
        return Response({
            'code':200,
            'msg':'获取单条部门信息成功',
            'data':{
                'id':department.id,
                'dname':department.dname
            }
        })
    @check_login
    def put(self,request,id):
        user_id = request.user_id
        if user_id == 1:
            dname = request.data.get('dname')
            department = DepartmentModel.objects.get(id=id)
            if not department:
                return Response({
                    'code':400,
                    'msg':'没有该部门'
                })
            if dname != department.dname:
                department.dname = dname
                department.save()
            return Response({
                'code':200,
                'msg':'修改成功'
            })
        else:
            return Response({
                'code':400,
                'msg':'对不起，您没有该权限'
            })
    @check_login
    def delete(self,request,id):
        user_id = request.user_id
        if user_id == 1:
            DepartmentModel.objects.filter(id=id).delete()
            return Response({
                'code':200,
                'msg':'删除部门成功'
            })
        else:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })


# 职级管理(查，增)
class RankView(APIView):
    def get(self,request):
        ranks = RankModel.objects.all()
        temp = []
        for item in ranks:
            temp.append({
                'id':item.id,
                'rname':item.rname
            })
        return Response({
            'code':200,
            'msg':'获取职级成功',
            'data':temp
        })
    @check_login
    def post(self,request):
        user_id = request.user_id
        if user_id == 1:
            rname = request.data.get('rname')
            if not rname:
                return Response({
                    'code':400,
                    'msg':'参数不完整'
                })
            rank = RankModel.objects.filter(rname=rname).first()
            if not rank:
                RankModel.objects.create(rname=rname)
                return Response({
                    'code':201,
                    'msg':'添加职级成功'
                })
            else:
                return Response({
                    'code':400,
                    'msg':'已有该职级'
                })
        else:
            return Response({
                'code': 400,
                'msg': '没有该权限'
            })


# 职级管理(查，改，删)
class RankInfoView(APIView):
    def get(self,request,id):
        rank = RankModel.objects.get(id=id)
        if not rank:
            return Response({
                'code':400,
                'msg':'没有该职级'
            })
        return Response({
            'code':200,
            'msg':'获取单条职级信息成功',
            'data':{
                'id':rank.id,
                'dname':rank.rname
            }
        })
    @check_login
    def put(self,request,id):
        user_id = request.user_id
        if user_id == 1:
            rname = request.data.get('rname')
            rank = RankModel.objects.get(id=id)
            if not rank:
                return Response({
                    'code':400,
                    'msg':'没有该职级'
                })
            if rname != rank.rname:
                rank.rname = rname
                rank.save()
            return Response({
                'code':200,
                'msg':'修改成功'
            })
        else:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
    @check_login
    def delete(self,request,id):
        user_id = request.user_id
        if user_id == 1:
            RankModel.objects.filter(id=id).delete()
            return Response({
                'code':200,
                'msg':'删除职级成功'
            })
        else:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })


# 岗位管理(查，增)
class PostView(APIView):
    def get(self,request):
        posts = PostsModel.objects.all()
        temp = []
        for item in posts:
            temp.append({
                'id': item.id,
                'pname': item.pname
            })
        return Response({
            'code': 200,
            'msg': '获取岗位成功',
            'data': temp
        })
    @check_login
    def post(self,request):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code':400,
                'msg':'对不起，您没有该权限'
            })
        pname = request.data.get('pname')
        if not pname:
            return Response({
                'code': 400,
                'msg': '参数不完整'
            })
        posts = PostsModel.objects.filter(pname=pname).first()
        if not posts:
            PostsModel.objects.create(pname=pname)
            return Response({
                'code': 201,
                'msg': '添加岗位成功'
            })
        else:
            return Response({
                'code': 400,
                'msg': '已有该岗位'
            })


# 岗位管理(查，改，删)
class PostInfoView(APIView):
    def get(self,request,id):
        posts = PostsModel.objects.get(id=id)
        if not posts:
            return Response({
                'code': 400,
                'msg': '没有该岗位'
            })
        return Response({
            'code': 200,
            'msg': '获取单条岗位信息成功',
            'data': {
                'id': posts.id,
                'dname': posts.pname
            }
        })
    @check_login
    def put(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        pname = request.data.get('pname')
        posts = PostsModel.objects.get(id=id)
        if not posts:
            return Response({
                'code':400,
                'msg':'没有该岗位'
            })
        if pname != posts.pname:
            posts.pname = pname
            posts.save()
        return Response({
            'code':200,
            'msg':'修改成功'
        })
    @check_login
    def delete(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        PostsModel.objects.filter(id=id).delete()
        return Response({
            'code':200,
            'msg':'删除岗位成功'
        })


# 权限管理(查，增)
class JurisdictionView(APIView):
    def get(self,request):
        juris = JurisdictionModel.objects.all()
        temp = []
        for item in juris:
            temp.append({
                'id':item.id,
                'jname':item.jname,
                'pathname':item.pathname
            })
        return Response({
            'code':200,
            'msg':'获取权限成功',
            'data':temp
        })

    @check_login
    def post(self,request):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        jname = request.data.get('jname')
        pathname = request.data.get('pathname')
        if not all([jname,pathname]):
            return Response({
                'code': 400,
                'msg': '参数不完整'
            })
        juri = JurisdictionModel.objects.filter(jname=jname).first()
        if not juri:
            JurisdictionModel.objects.create(jname=jname,pathname=pathname)
            return Response({
                'code': 201,
                'msg': '添加权限成功'
            })
        else:
            return Response({
                'code': 400,
                'msg': '已有该权限'
            })


# 权限管理(查，改，删)
class JurisdictionInfoView(APIView):
    def get(self,request,id):
        juri = JurisdictionModel.objects.get(id=id)
        if not juri:
            return Response({
                'code': 400,
                'msg': '没有该权限'
            })
        return Response({
            'code': 200,
            'msg': '获取单条权限信息成功',
            'data': {
                'id': juri.id,
                'jname': juri.jname,
                'pathname':juri.pathname
            }
        })
    @check_login
    def put(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        jname = request.data.get('jname')
        pathname = request.data.get('pathname')
        juri = JurisdictionModel.objects.get(id=id)
        if not juri:
            return Response({
                'code': 400,
                'msg': '没有该权限'
            })
        if jname != juri.jname:
            juri.jname = jname
            juri.save()
        if pathname != juri.pathname:
            juri.pathname = pathname
            juri.save()
        return Response({
            'code': 200,
            'msg': '修改成功'
        })
    @check_login
    def delete(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        JurisdictionModel.objects.filter(id=id).delete()
        return Response({
            'code': 200,
            'msg': '删除权限成功'
        })


# 角色管理(查，增)
class RoleView(APIView):
    def get(self,request):
        roles = RoleModel.objects.all()
        temp = []
        for item in roles:
            temp.append({
                'id':item.id,
                'roname':item.roname,
                'juris':item.juris.jname
            })
        return Response({
            'code':200,
            'msg':'获取角色成功',
            'data':temp
        })

    @check_login
    def post(self,request):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        roname = request.data.get('roname')
        juri = request.data.get('juri')
        if not all([roname,juri]):
            return Response({
                'code': 400,
                'msg': '参数不完整'
            })
        role = RoleModel.objects.filter(roname=roname).first()
        if not role:
            RoleModel.objects.create(roname=roname,juris_id=juri)
            return Response({
                'code': 201,
                'msg': '添加角色成功'
            })
        else:
            return Response({
                'code': 400,
                'msg': '已有该角色'
            })


# 角色管理(查，改，删)
class RoleInfoView(APIView):
    def get(self,request,id):
        role = RoleModel.objects.get(id=id)
        if not role:
            return Response({
                'code': 400,
                'msg': '没有该权限'
            })
        return Response({
            'code': 200,
            'msg': '获取单条角色信息成功',
            'data': {
                'id': role.id,
                'roname': role.roname,
                'juri':role.juris.id
            }
        })
    @check_login
    def put(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        roname = request.data.get('roname')
        juri = request.data.get('juri')
        role = RoleModel.objects.get(id=id)
        if not role:
            return Response({
                'code': 400,
                'msg': '没有该角色'
            })
        if roname != role.roname:
            role.roname = roname
            role.save()
        if juri != role.juris_id:
            role.juris_id = juri
            role.save()
        return Response({
            'code': 200,
            'msg': '修改成功'
        })
    @check_login
    def delete(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        RoleModel.objects.filter(id=id).delete()
        return Response({
            'code': 200,
            'msg': '删除角色成功'
        })


# 图片验证码
class ImageCodeView(APIView):
    def get(self,request,uuid):
        code = ''.join(random.sample(string.ascii_letters+string.digits,4))
        img = ImageCaptcha()
        image_code = img.generate(code)
        cls = redis.Redis(host='127.0.0.1',port=6379,password='qjr041014')
        cls.set(uuid,code,ex=5*60)
        return HttpResponse(image_code,content_type='image/png')


# 获取验证码
class SmsView(APIView):
    def get(self,request,mobile):
        uuid = request.query_params.get('uuid')
        img_code = request.query_params.get('img_code')
        if not all([uuid,img_code]):
            return Response({
                'code':400,
                'msg':'参数不完整'
            })
        cls = redis.Redis(host='127.0.0.1',port=6379,password='qjr041014')
        img_code1 = cls.get(uuid)
        if not img_code1:
            return Response({
                'code':400,
                'msg':'图形验证码已过期'
            })
        if img_code1.decode().lower() != img_code.lower():
            return Response({
                'code':400,
                'msg':'图形验证码错误'
            })
        send_message(mobile)
        return Response({
            'code':200,
            'msg':'发送成功'
        })


# 登录注册
class LoginView(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        code = request.data.get('code')
        department_id = request.data.get('department_id')
        rank_id = request.data.get('rank_id')
        role_id = request.data.get('role_id')
        post_id = request.data.get('post_id')
        if not all([mobile,code]):
            return Response({
                'code':400,
                'msg':'参数不完整'
            })
        cls = redis.Redis(host='127.0.0.1',port=6379,password='qjr041014')
        code1 = cls.get('sms_%s'%mobile)
        if not code1:
            return Response({
                'code':400,
                'msg':'验证码已过期'
            })
        if code1.decode() != code:
            return Response({
                'code':400,
                'msg':'验证码错误'
            })
        user = UserModel.objects.filter(mobile=mobile).first()
        if not user:
            username = '用户'+mobile[-4:]
            zhanghao = 'OA'+mobile[-4:]
            password = '123456'
            mail = str(random.randint(100000,999999))+'@qq.com'
            UserModel.objects.create(username=username,zhanghao=zhanghao,password=password,mail=mail,department_id=department_id,rank_id=rank_id,role_id=role_id,post_id=post_id)
        try:
            user = UserModel.objects.filter(mobile=mobile).first()
        except Exception as e:
            print(e)
            return Response({
                'code':400,
                'msg':"没有此用户信息"
            })
        token = jwt.encode({
            'user_id':user.id,
            'username':user.username,
            'exp':time.time()+7200
        },key=settings.SECRET_KEY,algorithm='HS256')
        return Response({
            'code':200,
            'msg':'登录成功',
            'token':token
        })


# 用户管理(查，增)
class UsersView(APIView):
    def get(self,request):
        users = UserModel.objects.all()
        temp = []
        states = ''
        for item in users:
            if item.state == '':
                states = '在职'
            elif item.state == '1':
                states = '离职'
            elif item.state == '2':
                states = '出差'
            elif item.state == '3':
                states = '请假'
            temp.append({
                'id':item.id,
                'username': item.username,
                'zhanghao': item.zhanghao,
                'mobile': item.mobile,
                'mail': item.mail,
                'department': item.department.dname,
                'rank':item.rank.rname,
                'role':item.role.roname,
                'post':item.post.pname,
                'state':states
            })
        return Response({
            'code':200,
            'msg':'获取用户信息成功',
            'data':temp
        })
    @check_login
    def post(self,request):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        username = request.data.get('username')
        zhanghao = request.data.get('zhanghao')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        mail = request.data.get('mail')
        department_id = request.data.get('department_id')
        rank_id = request.data.get('rank_id')
        role_id = request.data.get('role_id')
        post_id = request.data.get('post_id')
        state = request.data.get('state')
        if not all([username,zhanghao,password,mobile,mail,department_id,rank_id,role_id,post_id]):
            return Response({
                'code':400,
                'msg':'参数不完整'
            })
        user = UserModel.objects.filter(mobile=mobile).first()
        if not user:
            UserModel.objects.create(username=username,zhanghao=zhanghao,password=password,mobile=mobile,
                                     mail=mail,department_id=department_id,rank_id=rank_id,role_id=role_id,post_id=post_id,state=state)
            return Response({
                'code':201,
                'msg':'添加员工信息成功'
            })
        else:
            return Response({
                'code':400,
                'msg':'已有该员工信息'
            })


# 用户管理(查,改，删)
class UserInfoView(APIView):
    def get(self,request,id):
        user = UserModel.objects.get(id=id)
        if not user:
            return Response({
                'code':400,
                'msg':'没有该员工信息'
            })
        states = ''
        if user.state == '':
            states = '在职'
        elif user.state == '1':
            states = '离职'
        elif user.state == '2':
            states = '出差'
        elif user.state == '3':
            states = '请假'
        return Response({
            'code':200,
            'msg':'获取员工信息成功',
            'data':{
                'id': user.id,
                'username': user.username,
                'zhanghao': user.zhanghao,
                'mobile': user.mobile,
                'mail': user.mail,
                'department_id': user.department_id,
                'rank_id': user.rank_id,
                'role_id': user.role_id,
                'post_id': user.post_id,
                'state': states
            }
        })
    @check_login
    def put(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        username = request.data.get('username')
        zhanghao = request.data.get('zhanghao')
        mobile = request.data.get('mobile')
        mail = request.data.get('mail')
        department_id = request.data.get('department_id')
        rank_id = request.data.get('rank_id')
        role_id = request.data.get('role_id')
        post_id = request.data.get('post_id')
        state = request.data.get('state')
        user = UserModel.objects.get(id=id)
        if not user:
            return Response({
                'code': 400,
                'msg': '没有该员工信息'
            })
        if username != user.username:
            user.username = username
        if zhanghao != user.zhanghao:
            user.zhanghao = zhanghao
        if mobile != user.mobile:
            user.mobile = mobile
        if mail != user.mail:
            user.mail = mail
        if department_id != user.department_id:
            user.department_id = department_id
        if rank_id != user.rank_id:
            user.rank_id = rank_id
        if role_id != user.role_id:
            user.role_id = role_id
        if post_id != user.post_id:
            user.post_id = post_id
        if state != user.state:
            user.state = state
        user.save()
        return Response({
            'code':200,
            'msg':'修改成功'
        })
    @check_login
    def delete(self,request,id):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        user = UserModel.objects.get(id=id)
        user.state = '1'
        user.save()
        return Response({
            'code':200,
            'msg':'删除成功'
        })